<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <template slot="footer">
      <a-button key="close" @click="handleCancel">关闭</a-button>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-card :bordered="false">
        <a-timeline>
          <a-timeline-item v-for="item in progressList" :key="item.id" :color="getStatusColor(item.newStatus)">
            <div class="timeline-item">
              <div class="timeline-header">
                <span class="status">{{ getStatusText(item.newStatus) }}</span>
                <span class="time">{{ item.createTime }}</span>
              </div>
              <div class="timeline-content">
                <p>操作人: {{ item.operatorName || item.createBy_dictText || item.createBy || '系统' }}</p>
                <p v-if="item.changeReason">原因: {{ item.changeReason }}</p>
              </div>
            </div>
          </a-timeline-item>
          
          <a-timeline-item v-if="progressList.length === 0">
            <div class="empty-progress">
              <a-empty description="暂无进度记录" />
            </div>
          </a-timeline-item>
        </a-timeline>
        
        <!-- 分页 -->
        <a-pagination
          v-if="ipagination.total > 10"
          :current="ipagination.current"
          :pageSize="ipagination.pageSize"
          :total="ipagination.total"
          :showTotal="(total) => `共 ${total} 条`"
          :showSizeChanger="true"
          :pageSizeOptions="['10', '20', '30', '50']"
          @change="handleChange"
          @showSizeChange="handleShowSizeChange"
          style="margin-top: 16px; text-align: right;"
        />
      </a-card>
    </a-spin>
  </a-modal>
</template>

<script>
import { getAction } from '@/api/manage'
import { getDictItemsFromCache } from '@/components/dict/JDictSelectUtil'

export default {
  name: 'ProductOrderProgress',
  data() {
    return {
      title: '订单进度',
      visible: false,
      confirmLoading: false,
      progressList: [],
      orderId: '',
      ipagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      statusDictItems: [],
      url: {
        list: '/oms/productSalesOrder/progress/list',
        pageByOrderId: '/oms/productSalesOrder/progress/pageByOrderId',
        getEmployeeById: '/sys/employee/queryById'
      },
      // 用户信息缓存，避免重复请求
      userCache: {}
    }
  },
  created() {
    // 获取订单状态字典
    this.loadStatusDict()
  },
  methods: {
    show(id) {
      this.visible = true
      this.orderId = id
      this.loadData()
    },
    
    loadData() {
      this.confirmLoading = true
      let params = {
        orderId: this.orderId,
        pageNo: this.ipagination.current,
        pageSize: this.ipagination.pageSize
      }
      
      getAction(this.url.pageByOrderId, params).then(res => {
        if (res.success) {
          this.progressList = res.result.records || []
          this.ipagination.total = res.result.total || 0
          
          // 获取所有操作人的员工名称并设置
          this.processOperatorNames()
        } else {
          this.$message.warning(res.message || '获取订单进度失败')
          this.progressList = []
        }
        this.confirmLoading = false
      }).catch(err => {
        console.error('获取订单进度异常:', err)
        this.$message.error('获取订单进度失败')
        this.progressList = []
        this.confirmLoading = false
      })
    },
    
    // 获取所有操作人的员工名称
    processOperatorNames() {
      if (!this.progressList || this.progressList.length === 0) return
      
      this.progressList.forEach(item => {
        if (item.createBy && !item.operatorName) {
          this.getOperatorInfo(item)
        }
      })
    },
    
    // 获取操作人信息
    getOperatorInfo(item) {
      const userId = item.createBy
      
      // 检查缓存中是否已有此用户信息
      if (this.userCache[userId]) {
        item.operatorName = this.userCache[userId]
        return
      }
      
      // 调用接口获取用户信息
      getAction(this.url.getEmployeeById, { id: userId }).then(res => {
        if (res.success && res.result) {
          const employeeName = res.result.empName || res.result.username || userId
          // 保存到缓存
          this.userCache[userId] = employeeName
          // 设置操作人名称
          item.operatorName = employeeName
        }
      })
    },
    
    // 加载订单状态字典
    loadStatusDict() {
      this.statusDictItems = getDictItemsFromCache('order_status')
    },
    
    // 获取状态颜色
    getStatusColor(status) {
      if (!status && status !== 0) return 'blue'
      
      switch (parseInt(status)) {
        case 0: return 'blue' // 新增订单-待审核
        case 1: return 'green' // 审核通过-待上传
        case 2: return 'green' // 已上传汇总单-待上传优化单
        case 3: return 'green' // 已上传优化单-待提交审核
        case 4: return 'orange' // 待下发
        case 5: return 'orange' // 领料单待审核
        case 6: return 'orange' // 待领料
        case 7: return 'purple' // 生产中
        case 8: return 'cyan' // 已完成
        case 9: return 'red' // 已驳回
        default: return 'gray'
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      if (!status && status !== 0) return '未知状态'
      
      const statusNum = parseInt(status)
      // 首先从字典中查找
      const dictItem = this.statusDictItems.find(item => item.value == statusNum)
      if (dictItem) {
        return dictItem.text
      }
      
      // 如果字典中没有，使用内置映射
      switch (statusNum) {
        case 0: return '新增订单-待审核'
        case 1: return '审核通过-待上传'
        case 2: return '已上传汇总单-待上传优化单'
        case 3: return '已上传优化单-待提交审核'
        case 4: return '待下发'
        case 5: return '领料单待审核'
        case 6: return '待领料'
        case 7: return '生产中'
        case 8: return '已完成'
        case 9: return '已驳回'
        default: return '其他状态'
      }
    },
    
    // 分页处理
    handleChange(page) {
      this.ipagination.current = page
      this.loadData()
    },
    
    handleShowSizeChange(current, size) {
      this.ipagination.current = 1
      this.ipagination.pageSize = size
      this.loadData()
    },
    
    handleCancel() {
      this.visible = false
      this.progressList = []
      this.ipagination.current = 1
    }
  }
}
</script>

<style lang="less" scoped>
.timeline-item {
  padding: 12px;
  border-radius: 4px;
  background-color: #f9f9f9;
  margin-bottom: 8px;
  
  &:hover {
    background-color: #f0f2f5;
  }
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  
  .status {
    font-weight: bold;
    font-size: 16px;
  }
  
  .time {
    color: rgba(0, 0, 0, 0.45);
  }
}

.timeline-content {
  color: rgba(0, 0, 0, 0.65);
  
  p {
    margin-bottom: 4px;
  }
}

.empty-progress {
  padding: 20px 0;
}
</style> 